﻿using UnityEngine;
using System.Collections;
using Engine.Entities.Character;
using System.Collections.Generic;
using Assets.Engine.AI.GeneticAlgorithm;

public class UICoupleManager : MonoBehaviour {

    public UIButton ButtonCouple;
    public GameObject selectedMaleContainer;
    public GameObject selectedFemaleContainer;
    public GameObject UICharacter;
    public UIScrollBar scrollBarMale;
    public UIScrollBar scrollBarFemale;
    public UIGrid gridMale;
    public UIGrid gridFemale;
    public UIGrid gridSelectedMale;
    public UIGrid gridSelectedFemale;
    public GameObject world;
    public UISlider MixingRatio;
    public UISlider PercentageMutation;
    public UISlider RangeMutation;

    private FrenzyPeopleController peopleController;
    private SteveModel selectedMale = null;
    private SteveModel selectedFemale = null;
    private int cont = 0;
    private List<CoupleDragDropItem> ListMale = new List<CoupleDragDropItem>();
    private List<CoupleDragDropItem> ListFemale = new List<CoupleDragDropItem>();
    
    void Awake()
    {
        peopleController = world.GetComponent<FrenzyPeopleController>();
    }

	void Start () {
        Init();
	}
	
	void Update () {
	
	}

    private void Init()
    {
        selectedMale = null;
        selectedFemale = null;

        //pulisco i precedenti elementi
        Clear(gridMale);
        Clear(gridFemale);
        Clear(gridSelectedMale);
        Clear(gridSelectedFemale);

        scrollBarFemale.value = 0;
        scrollBarMale.value = 0;

        Reposition();
        ButtonCouple.isEnabled = false;

    }

    private void Clear( UIGrid grid )
    {
        List<Transform> tmpList = grid.GetChildList();
        
        foreach (Transform item in tmpList)
        {
            grid.RemoveChild(item);
            NGUITools.Destroy(item.gameObject);
            Destroy(item.gameObject);
            //NGUITools.DestroyImmediate(item);
            //Destroy(item);
        }
    }

    public void LoadPeople()
    {
        Init();
        _LoadPeople();
    }

    private void _LoadPeople()
    {
        Debug.Log("Carico " + peopleController.SteveList.Count + " oggetti");

        foreach (SteveBrain item in peopleController.SteveList)
        {
            UIGrid target;
            SteveModel model = item.model;
            
            //seleziona la griglia in cui attaccare l'oggetto
            if (model.Gender == GenderEnum.Male)
                target = gridMale;
            else
                target = gridFemale;

            GameObject newItem = AddItem(target, model);

            //copia il riferimento del buvo oggetto creato
            if (model.Gender == GenderEnum.Male)
                ListMale.Add(newItem.GetComponent<CoupleDragDropItem>());
            else
                ListFemale.Add(newItem.GetComponent<CoupleDragDropItem>());
        
        }

        Reposition();
        RefreshUI();

    }

    private void RefreshUI()
    {
        foreach (CoupleDragDropItem item in ListMale)
        {
            item.RefreshUI();
        }
        foreach (CoupleDragDropItem item in ListFemale)
        {
            item.RefreshUI();
        }
    }

    public GameObject AddItem(UIGrid target, SteveModel model, string name = null)
    {
        GameObject newChar = Instantiate(UICharacter);
        //newChar.transform.parent = target.transform;

        target.AddChild(newChar.transform);

        newChar.transform.localScale = new Vector3(1, 1, 1);
        newChar.transform.localPosition = new Vector3(0, 0, 0);

        if (name == null)
        {
            newChar.name = "char_" + cont;
            cont++;
        }
        else
            newChar.name = name;

        //assegno il contentuto dell' oggetto
        CoupleDragDropItem component = newChar.GetComponent<CoupleDragDropItem>();
        component.peopleCtrl = peopleController;
        component.Model = model;
        component.RefreshUI();

        return newChar;
    }

    /// <summary>
    /// Partendo dalla superfice selezionata, recupera la grid target e inserisce il nuovo oggetto
    /// </summary>
    /// <param name="gameObject"></param>
    /// <param name="surface"></param>
    /// <param name="model"></param>
    internal void AddSelectedItem(SteveModel model, GameObject cloneObject)
    {
        GameObject container = null;
        UIGrid gridTarget = null;
        
        if (model.Gender == GenderEnum.Male)
        {
            container = selectedMaleContainer;
            gridTarget = gridSelectedMale;
            selectedMale = model;
        }
        else
        {
            container = selectedFemaleContainer;
            gridTarget = gridSelectedFemale;
            selectedFemale = model;
        }
        
        //sovrascrive l'oggetto selezionato    
        Clear(gridTarget);
        GameObject newChar = AddItem(gridTarget, model, container.name);
        
        //elimina l'effetto sull'oggetto
        Destroy( newChar.GetComponent<UIButtonScale>() );

        //verifica se attivare l'accoppiamento
        if (selectedFemale != null && selectedMale != null)
            ButtonCouple.isEnabled = true;

    }

    private UIGrid GetUIGrid(GameObject container)
    {
        //prende il primo figlio del container 
        return container.transform.GetChild(0).GetComponent<UIGrid>();
    }

    private void Reposition()
    {
        gridMale.repositionNow = true;
        gridFemale.repositionNow = true;
        gridMale.Reposition();
        gridFemale.Reposition();
    }

    internal bool IsValidOperation(GameObject gameObject, GameObject surface, SteveModel steveModel)
    {
        //male   -> content male
        if (surface.name == selectedMaleContainer.name && steveModel.Gender == GenderEnum.Male)     return true;
        //female -> content female
        if (surface.name == selectedFemaleContainer.name && steveModel.Gender == GenderEnum.Female) return true;

        return false;
    }

    public void Couple()
    {
        GeneticVariables genvar = new GeneticVariables();
        genvar.MixingRatio = MixingRatio.value;
        genvar.PercentageMutation = PercentageMutation.GetComponent<PercentageController>().GetValue();
        genvar.MinMutation = (int)RangeMutation.GetComponent<RangeMutationController>().GetMin();
        genvar.MaxMutation = (int)RangeMutation.GetComponent<RangeMutationController>().GetMax();

        Genetic genetic = new Genetic(peopleController);
        SteveModel model = genetic.Couple(selectedMale, selectedFemale, genvar);
        peopleController.CreateCharacter(model);

        LoadPeople(); //refresh GUI
    }
}
